const mongoose = require("mongoose");
const db = require('./db.js');
const getDate = require("./date.js");
const token = require("./token.js");
let Schema = mongoose.Schema;

let UserShema = new Schema({
  uid: {
    type: String,
    index: true
  },
  nickname: String,
  password: String,
  colmenu: Array,
  lovedsong: Array,
  token: String,
  logintime: String,
});
let UserModel = db.model('User', UserShema);

class User {
  constructor(uid, nickname, password) {
    this.uid = uid;
    this.nickname = nickname;
    this.password = password;
  }
  signup() {
    var userEntity = new UserModel({
      uid: this.uid,
      nickname: this.nickname,
      password: this.password,
      colmenu: {},
      lovedsong: [],
      token: "",
      logintime: ""
    });
    var promise = userEntity.save();
    return promise.then((doc) => {
      if (doc.uid === this.uid) {
        return User.createToken(doc);
      } else {
        return 0;
      }
    }).catch((err) => {
      return 410; //410代表该用户已存在可以直接登录（即新用户存储失败）
    })
  }
}
//用于创建token并在数据库设置或者更新token，参数doc是一个user记录
User.createToken = (doc) => {
  const date = getDate();
  const newtoken = token(doc.uid, date.second);
  doc.token = newtoken;
  doc.logintime = date.second
  doc.save();
  return doc;
}
User.login = (uid, password) => {
  var userPro = UserModel.findOne({
    uid: uid
  }).exec();
  return userPro.then((doc) => {
    if(!doc){
      return 409;//409代表没有这个用户应该先注册
    }else if (doc.password === password ? 1 : 0) {
      return User.createToken(doc);
    }else {
      return 408; //408代表密码错误
    }
  }, (err) => {
    return 500;
  })
}
User.addLoved = (uid, songObj) => {
  if (!uid || !songObj.ID) {
    return 400;
  }
  var userPro = UserModel.findOne({
    uid: uid
  }).exec();
  return userPro.then((doc) => {
    return doc.lovedsong.unshift(songObj).save();
  });
}
User.addMenu = (uid, menuId) => {
  if (!uid || !menuId) {
    return 400;
  }
  var userPro = UserModel.findOne({
    uid: uid
  }).exec();
  return userPro.then((doc) => {
    return doc.colmenu.unshift(menuId).save();
  });
}
//检测当前token是否有效，如果有效返回这个用户的id
User.checkToken = (token) => {
  let promise = UserModel.findOne({
    token: token
  }).exec();
  return promise.then((doc) => {
    const newdate = new Date();
    if(!doc){
      return 2;
    }
    if ((newdate - new Date(doc.logintime)) / 1000 > 7200) {
      return 0;//token 过期，说明要重新登录
    }
    return doc; //这里返回0 代表token依旧有效
  }, () => {
    return 1;
  })
}
module.exports = User;